package cn.lanqiao.springboot.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ArticleService {

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    /**
     * 用户是否点过赞
     * article:1:userId(1,3,4)
     * userId:1:article(1,2,3)
     * article:1:likeCount
     *
     * @param articleId
     * @param userId
     */
    @Transactional
    public void articleLike(int articleId, int userId) {
        // 点赞
        // 1. 判断用户是否点过赞
        boolean isExist = redisTemplate.opsForSet().isMember("article:" + articleId, userId);
        if (isExist) {
            // 2. 如果点过赞，取消点赞
            redisTemplate.opsForSet().remove("article:" + articleId, userId);
            redisTemplate.opsForSet().remove("userId:" + userId, articleId);
            redisTemplate.opsForValue().decrement("article:" + articleId + ":likeCount");
        } else {
            // 3. 如果没点过赞，点赞
            redisTemplate.opsForSet().add("article:" + articleId, userId);
            redisTemplate.opsForSet().add("userId:" + userId, articleId);
            redisTemplate.opsForValue().increment("article:" + articleId + ":likeCount");
        }

    }


}
